<?php
require('includes/application_top.php');

if(MODULE_SEO_URL_INDEX_STATUS == 'True') {
	require_once(DIR_FS_INC.'inc.seo_url.php');
	!$seo_url ? $seo_url = new SeoUrl() : false;
}

require(DIR_WS_CLASSES.'class.import_products.php');
define('FILENAME_IMPORT_PRODUCTS', basename(__FILE__));
switch ($_GET['action'])
{
	case 'upload':
		$import = new ImportProductsBM();
		$import->log('start Import ..');
    $expected_post = array(
      array('field' => 'language',    'name' => 'language',     'default' => 1),
      array('field' => 'taxClass',    'name' => 'TAX_CLASS',    'default' => 1),
      array('field' => 'imgSrc',      'name' => 'IMG_SRC_PATH', 'default' => ''),
      array('field' => 'root',        'name' => 'ROOT',         'default' => 0),
      array('field' => 'testRun',     'name' => 'TEST_RUN',     'default' => 0),
      array('field' => 'clearFirst',  'name' => 'CLEAR_FIRST',  'default' => 0),
      array('field' => 'defStock',    'name' => 'DEF_STOCK',    'default' => 100),
      array('field' => 'isGross',     'name' => 'PRICE_TYPE',   'default' => 0)
    );

		$import->log("Parameter: \n" . print_r($_POST, true));
    foreach($expected_post as $post) {
  		$import->{$post['field']} = @$_POST[$post['name']] ? $_POST[$post['name']] : $post['default'];
    }
//echo_e($import);    
		if (!@$_FILES['file_upload']['tmp_name']) {
			$message_stack->add('Bitte geben Sie eine Import Datei an!', 'error');
			$import->log("FEHLER: keine Importdatei");
			break;
		}

		// 1st upload file
		if ($uploadFile = &try_upload('file_upload', DIR_FS_CATALOG.'import/')) {
			$uploadFileName = $uploadFile->filename;
			$uploadFileType = $uploadFile->file['type'];
			$import->log("Datei:  ". $uploadFileName . " - " . $uploadFileType);
    }
		else {
			$message_stack->add('Import fehlgeschlagen!', 'error');
			$import->log("FEHLER: Import fehlgeschlagen");
			break;		
		}

		// 2nd Import
		$total = $import->process(DIR_FS_CATALOG.'import/'.$uploadFileName, $uploadFileType);
		if ($total === false) {
			$message_stack->add($import->error, 'error');			
			$import->log("FEHLER: ".$import->error);
		} else {
			$message_stack->add($total.' Produkte erfolgreich importiert.', 'success');
			$import->log($total.' Produkte erfolgreich importiert!');
		}
//echo_e($message_stack, 'E');
		// 3rd delete file
		@unlink(DIR_FS_CATALOG.'import/'.$uploadFileName);
		$import->log($uploadFileName.' gelöscht!');
		break;
}

$sep_field = isset($_POST['SEP_FIELD']) ? $_POST['SEP_FIELD'] : ';';
$sep_text = isset($_POST['SEP_TEXT']) ? $_POST['SEP_TEXT'] : '"';
$def_stock = isset($_POST['DEF_STOCK']) ? $_POST['DEF_STOCK'] : '100';
$img_src_path = isset($_POST['IMG_SRC_PATH']) ? $_POST['IMG_SRC_PATH'] : '/_ftpaccounts/mercari/Informationsseite';
$root = isset($_POST['ROOT']) ? $_POST['ROOT'] : 0;

require_once(DIR_WS_INCLUDES.'/xajax/xajax_core/xajax.inc.php');
$xajax = new xajax();
require(DIR_FS_ADMIN.DIR_WS_INCLUDES.'xajax/xajax.folder.php');
$xajax->processRequest();
include(DIR_WS_INCLUDES.'metatag.php');
$xajax->printJavascript();
?>
<script type="text/javascript">
  $(document).ready(function(){
    if ($('input[name=IMG_SRC_PATH]').length > 0) {
      $('input[name=IMG_SRC_PATH]').attr({'id':'IMG_SRC_PATH', 'readonly': true}).click(
        function(){xajax_getFolderChilds(this.value)
      });

      $('#choosebox_imgpath ul').click( function(event) {
        $('#IMG_SRC_PATH').val($(event.target).html());
        $('#choosebox_imgpath').slideUp('slow');
        xajax_getFolderChilds($(event.target).html());
      });
      
      $('#choosebox_imgpath_close').click( function(event) {
        $('#choosebox_imgpath').slideUp('slow');
      });
    }
  });
  
  refreshFolderList = function(items) {
    $('#choosebox_imgpath').slideUp('slow', function(){
      $('#choosebox_imgpath ul li').remove()
      $('#choosebox_imgpath').slideDown('slow');

      $.each($.parseJSON(items), function(){
        $('#choosebox_imgpath ul').append('<li>'+this+'</li>');
      });
    });

  }
</script>
</head>
<body>
<?php require(DIR_WS_INCLUDES.'header.php'); ?>
<div id="wrapper">
<table class="outerTable" cellspacing="0" cellpadding="0">
	<td class="columnLeft2" width="<?php echo BOX_WIDTH; ?>" valign="top">
		<?php require(DIR_WS_INCLUDES.'column_left.php'); ?>
	</td>
	<td class="boxCenter" valign="top">
		<table width="100%">
			<tr><td>
				<table class="table_pageHeading" width="100%">
					<tr><td class="pageHeading">Import Produktdaten</td></tr>
				</table>
			</td></tr>
			<tr><td>
				<?php echo draw_form('upload', basename(__FILE__), 'action=upload', 'POST', 'enctype="multipart/form-data"'); ?>
				<table width="100%" cellspacing="2" cellpadding="5">
					<tr>
						<td colspan=3 style="padding-left: 25px">
						<i>Bitte bedenken Sie, dass jeder Artikel eine eindeutige Modellbezeichnung benötigt!<br /></i>
						</td>
					</tr>
					<tr>
					<td width="50">&nbsp;</td>
					<td width="150" class="infoBoxHeading">Bestand vorher bereinigen?</td>
					<td><?php echo draw_radio_field_jq('CLEAR_FIRST', array(0 => array('0', NO), 1 => array('1', YES)), (int)@$_POST['CLEAR_FIRST']); ?> (Produkte und Kategorien deaktivieren)</td>
					</tr>					
					<tr>					
					<td width="50">&nbsp;</td>
					<td width="150" class="infoBoxHeading">Import Datei auswählen (xls[x]):</td>
					<td><?php echo draw_file_field('file_upload'); ?></td>
					</tr>
					<!--tr>
					<td width="50">&nbsp;</td>
					<td width="150" class="infoBoxHeading">Trennzeichen</td>
					<td><?php echo draw_input_field('SEP_FIELD', $sep_field, 'size=3'); ?></td>
					</tr>
					<tr>
					<td width="50">&nbsp;</td>
					<td width="150" class="infoBoxHeading">Textbegrenzungszeichen</td>
					<td><?php echo draw_input_field('SEP_TEXT', $sep_text, 'size=3'); ?></td>
					</tr -->
					<tr>
					<td width="50">&nbsp;</td>
					<td width="150" class="infoBoxHeading">Steuerklasse*</td>
					<td><?php 
						$taxClasses = array();
						$result = $db->db_query("SELECT tax_class_id, tax_class_title FROM ".TABLE_TAX_CLASS." ORDER BY tax_class_id");
						while (!$result->EOF) {
							$taxClasses[] = array ('id' => $result->fields['tax_class_id'], 'text' => $result->fields['tax_class_title']);
							$result->MoveNext();
						}
						echo draw_pull_down_menu('TAX_CLASS', $taxClasses, '');
					?></td>
					</tr>
					<tr>
					<td width="50">&nbsp;</td>
					<td width="150" class="infoBoxHeading">Lagerwert*</td>
					<td><?php echo draw_input_field('DEF_STOCK', $def_stock, 'size=9'); ?></td>
					</tr>		
					<tr>
					<td width="50">&nbsp;</td>
					<td width="150" class="infoBoxHeading">Pfad zu den Bildern</td>
					<td>
            <?php echo draw_input_field('IMG_SRC_PATH', $img_src_path, 'style="width:500px"'); ?>
            <div id="choosebox_imgpath" style="min-width:497px;background:#fff;border:1px solid #000;position:absolute;display:none;z-index:500">
            <div id="choosebox_imgpath_close" style="position:absolute;left:3px;top:0px;cursor:pointer;">[x]</div>
            <ul style="list-style:none;margin-left:5px;margin-top:23px">
              <li>.</li>
            </ul>
            </div>
          </td>
					</tr>	
					<tr>
					<td width="50">&nbsp;</td>
					<td width="150" class="infoBoxHeading">Sprache</td>
					<td><?php 
						$languages = array();
						$result = $db->db_query("SELECT languages_id, name FROM ".TABLE_LANGUAGES." ORDER BY sort_order");
						while (!$result->EOF) {
							$languages[] = array ('id' => $result->fields['languages_id'], 'text' => $result->fields['name']);
							$result->MoveNext();
						}
						echo draw_pull_down_menu('language', $languages, '');
					?></td>
					</tr>					
					<tr>
					<td width="50">&nbsp;</td>
						<td width="150" class="infoBoxHeading">Preise sind </td>
					<td><?php 
						$temp = array();
						$temp[] = array ('id' => '1', 'text' => 'Brutto Preise');
						$temp[] = array ('id' => '0', 'text' => 'Netto Preise');
						echo draw_pull_down_menu('PRICE_TYPE', $temp, 'GROSS');
					?></td>
					</tr>
					<tr>
					<td width="50">&nbsp;</td>
					<td width="150" class="infoBoxHeading">Vater - Kategorie</td>
					<td><?php 
						echo draw_pull_down_menu('ROOT', ImportProducts::getCategories(), $root);
					?></td>
					</tr>
					<tr>
					<td width="50">&nbsp;</td>
					<td width="150" class="infoBoxHeading">Testlauf</td>
					<td><?php echo draw_radio_field_jq('TEST_RUN', array(0 => array('0', NO), 1 => array('1', YES)), (int)@$_POST['TEST_RUN']); ?> (nur das erste Produkt behandeln)</td>
					</tr>					
					<tr>
					<td width="50">&nbsp;</td>
					<td width="150">&nbsp;</td>
					<td>
					<?php
						echo '<br/><button type="submit" class="button" onclick="this.blur();"><span class="button_upload">Importieren</span></button>';
					?>
          <br />
          <br /><i>*wird nur beim initialen Import (neu oder nach Bereinigung) beachtet</i>
          <br /><i>Je nach Anzahl der Produkte kann der Import einige Zeit in Anspruch nehmen.</i>

					</td>
					</tr>
				</table>
				<?php echo '</form>'; ?>
			</td></tr>
		</table>
	</td>
	</table>
</div>
<?php require(DIR_WS_INCLUDES.'footer.php'); ?>
</body>
</html>
<?php require(DIR_WS_INCLUDES.'application_bottom.php'); ?>